<?php

namespace common\observer;

use common\model\StepModel;
use support\SingletonTrait;
use common\model\EntityModel;
use common\model\StepWorkflowModel;
use common\service\CommonService;
use common\service\OptionsService;
use common\service\StatusService;
use teamones\dbeventObserver\interfaces\SplSubject;
use teamones\dbeventObserver\interfaces\SplObserver;

/**
 * 动捕任务完成 同步动捕任务状态到动捕实体
 */
class MotionSequenceTaskDoneSyncStatusToSequenceEntity implements SplObserver
{
    use SingletonTrait;

    /**
     * @inheritDoc
     */
    function update(SplSubject $subject): void
    {
        $updateData = $subject->getSplUpdateData();
        if (!isset($updateData['task_status'])) {
            return;
        }
        $task = $subject->getSubjectData();
        $doneStatus = StatusService::getInstance()->getTaskDoneStatus();
        if (empty($doneStatus)) {
            return;
        }
        $motionTrackTaskCode = OptionsService::getInstance()->getOptionsConfigItemData('task_config', 'motion_task_step_code', 'motion_track');
        $motionTrackTaskStep = model(StepModel::class)->where(['code' => $motionTrackTaskCode])->find();
        // 判断是否为动捕任务完成
        if (empty($motionTrackTaskStep) || $task['step_id'] != $motionTrackTaskStep['id'] || $updateData['task_status'] != $doneStatus['id']) {
            return;
        }

        try {
            $entity = model(EntityModel::class)->where('id,step_workflow_id')->find($task['entity_id']);
            if (empty($entity) || empty($entity['step_workflow_id'])) {
                return;
            }
            $motionVersionSequenceStepWorkflowCodeConfig = OptionsService::getInstance()->getOptionsConfigItemData('task_config', 'motion_sequence_step_workflow_code', 'motion_sequence');
            $stepWorkflow = model(StepWorkflowModel::class)->where(['code' => $motionVersionSequenceStepWorkflowCodeConfig])->find();
            if (empty($stepWorkflow)) {
                return;
            }
            if ($stepWorkflow['id'] != $entity['step_workflow_id']) {
                return;
            }
            \request()->getModuleCode('sequence');
            $commonService = CommonService::instance('entity');
            $entityUpdateData = [
                'id' => $entity['id'],
                'sequence_status' => $doneStatus['id'],
            ];
            $commonService->update($entityUpdateData, 'sequence', false);
        } catch (\Throwable $e) {
            trace(format_exception_info($e), 'ERR');
        }
    }
}
